<template>
  <div>
    <el-row type="flex" class="row-bg" :gutter="20">
      <el-col :span="8">
        <div class="left-column">
          <!-- 日期卡片内容 -->
          <el-card class="box-card mb-20">
            <div class="date-container">
              <div class="current-date">{{ currentDate }}</div>
              <div class="current-week">{{ currentWeek }}</div>
            </div>
          </el-card>
          <el-card class="box-card">
            <div class="user-info">
              <div class="realname">用户：{{ loginUsername }}</div>
              <div class="role">角色：{{ loginRole }}</div>
            </div>
          </el-card>
        </div>
      </el-col>

      <el-col :span="16">
        <el-card class="box-card tall-card">
          <div slot="header" class="clearfix">
            <span>公告</span>
            <el-button
              v-if="isTeacherOrAdmin"
              type="primary"
              size="mini"
              icon="el-icon-plus"
              @click="showAddDialog"
              style="float: right;"
            >
              添加公告
            </el-button>
          </div>
          <div v-for="item in noticeListInfo" :key="item.noticeid" class="text item">
            <el-button
              type="text"
              @click="showNoticeDetail(item)"
              class="notice-title"
            >
              {{ item.title }}
            </el-button>
            <div v-if="isAdminOrSuperAdmin" class="notice-actions">
              <el-button
                type="text"
                icon="el-icon-edit"
                @click="showEditDialog(item)"
                class="action-btn"
              >
                编辑
              </el-button>
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="confirmDelete(item.noticeid)"
                class="action-btn delete-btn"
              >
                删除
              </el-button>
            </div>
          </div>

          <!-- 详情弹窗 -->
          <el-dialog
            :title="currentNotice.title"
            :visible.sync="dialogVisible"
            width="40%"
            top="5vh"
          >
            <div class="dialog-header">
              <div class="meta-info">
                <span class="publisher">发布者:{{ currentNotice.publisherid }}</span>
                <span class="publish-time">发布时间:{{ formattedTime }}</span>
              </div>
            </div>
            <div class="content-box">
              {{ currentNotice.content }}
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">关 闭</el-button>
            </span>
          </el-dialog>
          <!-- 添加公告弹窗 -->
          <el-dialog
            title="添加公告"
            :visible.sync="addDialogVisible"
            width="40%"
            top="5vh"
          >
            <el-form ref="addForm" :model="addForm" :rules="formRules">
              <el-form-item label="标题" prop="title">
                <el-input v-model="addForm.title" placeholder="请输入标题"></el-input>
              </el-form-item>
              <el-form-item label="内容" prop="content">
                <el-input
                  type="textarea"
                  v-model="addForm.content"
                  placeholder="请输入内容"
                  :rows="5"
                ></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="addDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addNotice">确 定</el-button>
            </span>
          </el-dialog>

          <!-- 编辑公告弹窗 -->
          <el-dialog
            :title="'编辑公告：' + editForm.title"
            :visible.sync="editDialogVisible"
            width="40%"
            top="5vh"
          >
            <el-form ref="editForm" :model="editForm" :rules="formRules">
              <el-form-item label="标题" prop="title">
                <el-input v-model="editForm.title"></el-input>
              </el-form-item>
              <el-form-item label="内容" prop="content">
                <el-input
                  type="textarea"
                  v-model="editForm.content"
                  :rows="5"
                ></el-input>
              </el-form-item>
              <el-form-item label="状态">
                <el-radio-group v-model="editForm.status">
                  <el-radio label="草稿">草稿</el-radio>
                  <el-radio label="已发布">已发布</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="resetEditForm">重 置</el-button>
              <el-button @click="editDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="updateNotice">确 定</el-button>
            </span>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginUsername: localStorage.getItem('realname') || '未登录',
      loginRole: localStorage.getItem('role') || '普通用户',
      currentDate: '',
      currentWeek: '',
      noticeListInfo: [],
      dialogVisible: false,
      currentNotice: {
        title: '',
        content: '',
        publisherid: '',
        publishtime: ''
      },
      // 角色控制相关
      userRole: localStorage.getItem('role') || '',
      userId: localStorage.getItem('userid') || '',

      // 添加公告表单
      addDialogVisible: false,
      addForm: {
        title: '',
        content: ''
      },

      // 编辑公告表单
      editDialogVisible: false,
      editForm: {
        noticeid: '',
        title: '',
        content: '',
        status: '草稿'
      },
      // 表单验证规则
      formRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      },

      // 保存原始编辑数据（用于重置）
      originalEditForm: null
    }
  },
  computed: {
    // 教师、管理员、超级管理员可见添加按钮
    isTeacherOrAdmin() {
      return ['教师', '管理员', '超级管理员'].includes(this.userRole);
    },

    // 管理员和超级管理员可见编辑删除按钮
    isAdminOrSuperAdmin() {
      return ['管理员', '超级管理员'].includes(this.userRole);
    },
    formattedTime() {
      if (!this.currentNotice.publishtime) return ''
      const date = new Date(this.currentNotice.publishtime)
      return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
    }
  },
  created() {
    this.loadNotice();
  },
  methods: {
// 显示添加公告弹窗
    showAddDialog() {
      this.addDialogVisible = true;
      if (this.$refs.addForm) {
        this.$refs.addForm.resetFields();
      }
    },

    // 添加公告
    addNotice() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          const noticeData = {
            ...this.addForm,
            publisherid: parseInt(this.userId),
            status: '草稿'
          };

          this.$axios.post("/notice/add", noticeData)
            .then(response => {
              if (response.data.state === 'success') {
                this.$message.success('公告添加成功');
                this.loadNotice();
                this.addDialogVisible = false; // 添加成功后关闭弹窗
              } else {
                this.$message.error('公告添加失败');
              }
            })
            .catch(error => {
              console.error("添加公告失败：", error);
              this.$message.error('公告添加失败');
            });
        }
      });
    },

    // 显示编辑公告弹窗
    showEditDialog(notice) {
      this.editForm = {
        noticeid: notice.noticeid,
        title: notice.title,
        content: notice.content,
        status: notice.status
      };

      // 保存原始数据用于重置
      this.originalEditForm = { ...this.editForm };
      this.editDialogVisible = true;
    },

    // 重置编辑表单
    resetEditForm() {
      if (this.originalEditForm) {
        this.editForm = JSON.parse(JSON.stringify(this.originalEditForm));
      } else if (this.$refs.editForm) {
        this.$refs.editForm.resetFields();
      }
    },

    // 更新公告
    updateNotice() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$axios.post("/notice/update", this.editForm)
            .then(response => {
              if (response.data.state === 'success') {
                this.$message.success('公告更新成功');
                this.loadNotice();
                this.editDialogVisible = false;
              } else {
                this.$message.error('公告更新失败');
              }
            })
            .catch(error => {
              console.error("更新公告失败：", error);
              this.$message.error('公告更新失败');
            });
        }
      });
    },

    // 确认删除公告
    confirmDelete(noticeid) {
      this.$confirm('确定要删除该公告吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteNotice(noticeid);
      }).catch(() => {});
    },

    // 删除公告
    deleteNotice(noticeid) {
      this.$axios.delete(`/notice/delete?noticeid=${noticeid}`)
        .then(response => {
          if (response.data.state === 'success') {
            this.$message.success('公告删除成功');
            this.loadNotice();
          } else {
            this.$message.error('公告删除失败');
          }
        })
        .catch(error => {
          console.error("删除公告失败：", error);
          this.$message.error('公告删除失败');
        });
    },

    // 加载公告
    async loadNotice() {
      try {
        const role = localStorage.getItem('role') || '';
        const response = await this.$axios.get("/notice/selectAll", {
          params: { role }
        });
        this.noticeListInfo = response.data.noticeListInfo || [];
      } catch (error) {
        console.error("获取公告失败：", error);
        this.$message.error('获取公告失败');
      }
    },
    // 更新日期
    updateDateTime() {
      const date = new Date();
      this.currentDate = date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      });
      this.currentWeek = '星期' + '日一二三四五六'[date.getDay()];
    },

    // async loadNotice() {
    //   try {
    //     const response = await this.$axios.get("http://localhost:8088/notice/selectAll");
    //     this.noticeListInfo = response.data.noticeListInfo;
    //   } catch (error) {
    //     console.error("获取公告失败：", error);
    //   }
    // },
    showNoticeDetail(notice) {
      this.currentNotice = { ...notice }
      this.dialogVisible = true
    }
  },
  mounted() {
    this.updateDateTime();
    // 每秒更新一次（可选）
    setInterval(this.updateDateTime, 1000);
  }
}
</script>

<style>
/* Notice.vue */
.notice-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  padding: 12px 0;
}

.notice-title {
  flex-grow: 1;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.notice-actions {
  flex-shrink: 0;
  margin-left: 10px;
}

/* 公告项样式 */
.notice-item {
  border-bottom: 1px solid #ebeef5;
  padding: 12px 0;
}

.notice-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notice-actions {
  display: flex;
}

.action-btn {
  padding: 0 5px;
}

.delete-btn {
  color: #F56C6C;
}

/* 弹窗标题居中 */
.el-dialog__header {
  text-align: center;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: 600;
}
/* 登录卡片样式修改开始 */
.user-info {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center; /* 水平居中 */
  justify-content: center; /* 垂直居中 */
  height: 100%; /* 确保容器充满卡片高度 */
  text-align: center; /* 文本居中 */
}
.realname, .role {
  font-size: 16px;
  color: #606266;
  margin: 8px 0; /* 增加上下间距 */
}
/* 登录卡片样式修改结束 */

/* 用户信息样式开始 */
.user-info {
  padding: 20px;
  line-height: 1.8;
}
.username, .role {
  font-size: 16px;
  color: #606266;
}
/* 用户信息样式结束 */
/* 日期样式开始 */
.date-container {
  text-align: center;
  padding: 20px;
}
.current-date {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
}
.current-week {
  font-size: 16px;
  color: #909399;
}
/* 日期样式结束 */
.notice-title {
  width: 100%;
  text-align: left;
  padding: 12px 0;
}

.dialog-header {
  margin-bottom: 20px;
}

.meta-info {
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}

.content-box {
  line-height: 1.8;
  min-height: 100px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-top: 15px;
}

/* 对话框标题居中 */
.el-dialog__header {
  text-align: center;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: 600;
}
</style>
